import React, { useEffect, useRef, useState } from 'react';

import { Button, Divider, Form, message, Row } from 'antd';
import { size } from 'lodash';
import { useMount } from 'react-use';
import { withRouter } from 'umi';

import { BottomAction } from '@/components';
import { defaultFormatResult, useRequest } from '@/hooks';
import { PageContainer } from '@/molecules';
import EmployeeCard from '@/pages/EntryManage/components/EmployeeCard';
import useCandidateProcess from '@/pages/EntryManage/hooks/useCandidateProcess';
import { getSoft } from '@/pages/EntryManage/services';
import { replaceToWaitEntry } from '@/pages/EntryManage/utils';

import Card from '../../components/Card';
import Equipment from '../component/Equipment';
import SendBackModal from '../component/SendBackModal';
import SoftwarePreinstall from '../component/SoftwarePreinstall';
import styles from '../index.less';
import { getEquipment, getSoftSelected, postIt } from '../services';
import DeviceConfigTable from './components/DeviceConfigTable';
import VirtualPropertyTable from './components/VirtualPropertyTable';

const formItemLayout = {
    labelCol: {
        span: 2
    },
    wrapperCol: {
        span: 22
    }
};
// IT准备
const PROCESS_STATUS = 3;
/**
 * IT准备
 * /office/personnelManagement/onboardAndLeave/entryManage/itDepartment
 */
const ItDepartment = ({ form, location }) => {
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { employeeCode } = user;
    const { validateFieldsAndScroll } = form;
    const [softTableData, setSoftTableData] = useState([]);
    const { entryPersonnelCode } = location.query;
    const [loadingType, setLoadingType] = useState(0);

    const sendBackRef = useRef();
    const refTable = React.useRef();

    // 获取通用软件
    const { data: softList, run: fetchSoft } = useRequest(() => getSoft({ entryPersonnelCode }), {
        manual: true,
        ...defaultFormatResult
    });
    // 获取已选择软件
    const { loading: softLoading, data: softSelectedList, run: fetchSoftSelected } = useRequest(
        () => getSoftSelected({ entryPersonnelCode }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取设备
    const { loading: deviceDataLoading, data: deviceData, run: fetchEquipment } = useRequest(
        () => getEquipment({ entryPersonnelCode, choiceType: '' }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 提交it准备
    const { run: submitIt, loading } = useRequest(value => postIt(value), {
        manual: true,
        onSuccess: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success(msg);
                    replaceToWaitEntry();
                } else {
                    message.error(msg);
                }
            }
        }
    });
    // 校验是否当前是否可以提交
    const canAction = useCandidateProcess(entryPersonnelCode, PROCESS_STATUS, employeeCode);

    const handleSubmit = type => {
        setLoadingType(type);
        const param = {
            currentHandlerEmployeeCode: employeeCode,
            entryPersonnelCode,
            temporaryStorage: type,
            entryStatus: 3 // IT准备为3
        };
        // type === 1 为暂存 不做校验

        if (type === 1) {
            const { assetList = [], systemList } = form.getFieldsValue();
            const data = assetList.filter(Boolean).map(item => ({
                assetCode: item?.assetCode,
                modelCode: item?.modelCode,
                assetNumber: item?.assetNumber,
                assetType: item?.assetType,
                entryStatus: 3,
                required: item?.required,
                id: item?.id
            }));
            submitIt({
                systemList,
                ...param,
                assetList: data
            });
            return;
        }
        validateFieldsAndScroll({ scroll: { alignWithTop: true } }, (err, values) => {
            if (!err) {
                const { assetList = [], systemList } = values;
                const data = assetList.filter(Boolean).map(item => ({
                    assetCode: item?.assetCode,
                    modelCode: item?.modelCode,
                    assetNumber: item?.assetNumber,
                    assetType: item?.assetType,
                    entryStatus: 3,
                    required: item?.required,
                    id: item?.id
                }));
                submitIt({
                    systemList,
                    ...param,
                    assetList: data
                });
            }
        });
    };

    useMount(() => {
        fetchEquipment();
        fetchSoft();
        fetchSoftSelected();
    });

    useEffect(() => {
        if (size(softList) > 0) {
            // 将数据源进行分类
            setSoftTableData(softList.filter(item => item.softClass === 0));
        }
    }, [softList]);

    return (
        <PageContainer>
            <EmployeeCard employeeCode={entryPersonnelCode} isShowControls={false} style={{ marginBottom: '20px' }} />
            <Divider />
            <Card bordered={false} headBorder>
                <Row>
                    <Form {...formItemLayout}>
                        <Card
                            className={styles.cardBox}
                            headBorder
                            bordered={false}
                            title="电脑配备"
                            loading={deviceDataLoading}
                            extra={
                                canAction ? (
                                    <BottomAction>
                                        <span className={styles.autoNotice}>自动通知行政负责人</span>
                                        <Button
                                            onClick={() => {
                                                sendBackRef.current.show();
                                            }}
                                        >
                                            退回
                                        </Button>
                                        <Button
                                            type="link"
                                            style={{ border: '1px solid #FF9E00' }}
                                            onClick={() => handleSubmit(1)}
                                            loading={loading && loadingType === 1}
                                        >
                                            保存
                                        </Button>
                                        <Button
                                            type="primary"
                                            onClick={() => handleSubmit(0)}
                                            loading={loading && loadingType === 0}
                                        >
                                            确定
                                        </Button>
                                    </BottomAction>
                                ) : null
                            }
                        >
                            <Equipment data={deviceData} />
                        </Card>
                        <Form.Item>
                            <DeviceConfigTable
                                entryPersonnelCode={entryPersonnelCode}
                                canAction={canAction}
                                form={form}
                                ref={refTable}
                            />
                        </Form.Item>
                        <Card
                            title="预装软件"
                            headBorder
                            bordered={false}
                            className={styles.cardBox}
                            loading={softLoading}
                        >
                            <SoftwarePreinstall selected={softSelectedList} tableData={softTableData} />
                        </Card>

                        <Card title="虚拟资产" headBorder bordered={false}>
                            <div>请为新员工开通以下账号，并提供初始密码</div>
                            <Form.Item>
                                <VirtualPropertyTable
                                    entryPersonnelCode={entryPersonnelCode}
                                    form={form}
                                    canAction={canAction}
                                />
                            </Form.Item>
                        </Card>
                    </Form>
                </Row>
            </Card>
            <SendBackModal
                entryPersonnelCode={entryPersonnelCode}
                wrappedComponentRef={sendBackRef}
                waringMessage="退回至部门准备，重新提交准备内容"
            />
        </PageContainer>
    );
};
export default withRouter(Form.create()(ItDepartment));
